<?php
namespace Mobile\Controller;
use Think\Controller;
use Mobile\Controller\WechatController;

use Mobile\Model\configModel;
use Mobile\Model\memberModel;
use Mobile\Model\tmplModel;

use Mobile\Model\cartModel;
use Mobile\Model\langModel;

class BaseController extends Controller{
	public $openid;
	public $unionid;
	public $uid;
	public $memberinfo;
	public $wxuserinfo;
	public $appid;
	public $appkey;
	public $wechat;
	public $memberModel;
	public $configModel;
	public $tmpl;
	public $contro;
	public $action;
	public $cartModel;
	public $langModel;

	//不需要登录的控制器,*匹配所有action(会尝试登录,如不能登录页没关系)
	public $no_need_login = array(
	    "order/callback",
	    "msg/*",
	    "user/grade",
	    "ordercallback/callback",
	    "ordercallback/test",
	    "ordercallback/cronupgrade",
	    "charge/callback",
	    "carhouse/*",
	    "ordershouhuo/cronshouhuo",
	    "ordercancel/croncloseorder",
	    "article/*",
	    "guestbook/ajaxadd",
	    "guestbook/cronguishudi",
            "weixin/*",
	    "check/*",
//	    "index/*",
	    "user/cronupgrade",
	    //"qrcode/*",
            "article/downloadpic",
	    "article/qrcodeapi",
	    //"article/qrcodeapi",
	    "address/createarea",
	    "address/createshipping",
	    "scancallback/index",
	    "cron/*",
	    "qrcode/userqrcode",
	    "zhengshu/*",
	    "article/qrcodeapi",
	    "ordercallback/cronupgrade",
            "orderadd/test",
	    "orderhm/callback",
	    'login/*',
            "bind/getopenid",
	    "orderhm/wangyincallback",
            'user/app',
            "backopen/index"
	);
	
	
	public function __construct($option='') {
		
	    C('VIEW_PATH','./Theme/mobile/');//模板文件目录
	    
	    $this->_getConfig();//获取配置文件
	    
	    //读取模板id并缓存
	    $tmpl = S("TMPL");
	    if(empty($tmpl) || 1){
	        $tmpl = $this->_getTmpId();//获取模板id
	        S("TMPL",$tmpl);
	    }
	    $this->tmpl = $tmpl;
	    
	    parent::__construct();
	    
	    //判断网站是否关闭
	    $is_close  = C("IS_CLOSED");
	    if($is_close == 1){
	        //网站关闭
	        $msg = C("CLOSED_REASON") ? C("CLOSED_REASON") : "网站暂时关闭,请联系客服";
	        $this->error2($msg);
	    }
	    
	    $controller = strtolower(CONTROLLER_NAME);//转成小写
	    $action = strtolower(ACTION_NAME);//转成小写
	    $this->contro = $controller;
	    $this->action = $action;
	    $this->assign('action',$action);
	    $this->assign('controller',$controller);
	    
	    //获取语言包
	    $this->_getLang("cn");
	    
	    $this->assign("jquery",true);
	    $this->assign("mui_css",true);
	    
	    $appid = C("WECHAT_APPID");
	    $appkey = C("WECHAT_APPKEY");
	    $this->appid = $appid;
	    $this->appkey = $appkey;
	    
	    $this->memberModel = new memberModel();

	    //TODO,注意此处提交时要注释掉
	    //$this->uid = 10002 ;//4513
	    //$this->memberinfo = $this->getMemberInfobyUid($this->uid);//TODO,正式环境注释
	    $this->is_wechat = is_platform("wechat");
	    $this->assign("is_wechat",$this->is_wechat);
	    if($option['baodan']) {
                return true;
            }
            if(!IS_AJAX){
	        layout('Common/layout');
	    }
            $is_mobile = is_mbile();
            $this->assign('is_mobile',$is_mobile);
	  
	    //如果是微信平台
	    if($this->is_wechat){
	        $this->wechat = new WechatController();
	         //自动登录
	         $user_new = session('wxuserinfo');
	         $this->wxuserinfo = $user_new;//微信用户信息
	         $this->assign('wxuserinfo',$user_new);
	         $this->openid = session('openid');
	         $this->unionid = session('unionid');
	         $this->uid = session('uid');
	         $this->memberinfo = session('memberinfo');
	         if($controller == 'check'){
	             //当前控制器不做跳转
	             return true;
	         }
	         
	         if(!$this->_isNeedLogin() || $controller == 'check'){
	             //需要登录
	             $res = $this->autoLogin();
	         }
                
	        //微信分销sdk
	        $jssign = $this->_sharesdk();
	    }else{
                if($controller == 'login'){
                    return true;
                }else{
                    $this->autoLogin(true);
                }
            }
            if($this->_isNeedLogin()){
                return true;
            }

            if($this->memberinfo) {
                $adStatus = C('AD_STATUS');
                $adImgUrl = C('AD_IMG_URL');
                
                if($adImgUrl && $adStatus==1) {
                    if(!session('showad')) {
                        $this->assign('showad',1);
                    }
                    session('showad', 1);
                }
                $this->_checkPassword();
            }
           
            
        
	    //刷新用户信息
	    $this->updateMemberSession($this->uid);
	    //获取购物车中有多少件商品
	    $this->cartModel = new cartModel();
	    $cartNum = $this->getCartNum();//获取购物车商品数量
	    $cartNum = $cartNum ? $cartNum : 0;
	    $this->assign("cartNum",$cartNum);
		
	}
	
        protected function _checkPassword () {
            $init = md5('123456'.C("SALT"));
            if($init == $this->memberinfo['password']) {
                $this->redirect('/mobile/login/changepw?new=1&mobile='.$this->memberinfo['mobile']);
            }
        }

        /*
	 * 检查是否需要登录
	 *
	 */
	protected function _isNeedLogin(){
	    $controller = strtolower(CONTROLLER_NAME);//转成小写
	    $action = strtolower(ACTION_NAME);//转成小写
	
	    if(in_array($controller."/".$action, $this->no_need_login) || in_array($controller."/*", $this->no_need_login)){
	        //当前控制器不需要登录
	        return true;
	    }
	    return false;
	}
	
	
	/*
	 * 自动登录
	 */
	public function autoLogin($re=false){
		
	    //判断是否登录
	    $this->memberinfo = session('memberinfo');
	    $this->uid = session('uid');
	    $this->unionid = session('unionid');
	    $this->openid = session('openid');
            $this->wxuserinfo = session('wxuserinfo');
            
	    if(!empty($this->memberinfo['uid'])){
	        //已经登录过了
	        return true;
	    }
		
	    if($re){
                if(!$this->_isNeedLogin()){
                    header('Location: /mobile/login');exit;
                }
	        return true;
	    }
		
	
	    //未登录
	    $state = get('state');
	    $session_state = session("state");
	    $code = get("code");
	
	    if(!$state || ($state != $session_state) || !$code){
	        //1. 获取授权地址
	        $state = token();//生成随机state
	        session("state",$state);
	        $scope = "snsapi_base";//  snsapi_userinfo
	        $callback =  get_this_url();
	        $oauth_url = $this->wechat->getOauthRedirect($callback,$state,$scope);// 获取网页授权oAuth跳转地址
	        header('Location: ' . $oauth_url);//去授权页面
	        exit;
	    }
	
	    $access_token = $this->wechat->getOauthAccessToken();
	    $openid = set_default($access_token,'openid');
	    $unionid = set_default($access_token,'unionid');//联合id
		
	    if(!$access_token || !$openid){
	        return false;
	    }
	     
	    //获取微信信息成功
	    $this->openid = $openid;
	    $this->unionid = $unionid;
	
	    session('unionid',$unionid);
	    session('openid',$openid);
		
	    //获取最新信息(关注者信息接口)
	    $user_new = $this->_get_user_info($access_token);
	    if($user_new){
	        $user_data = $user_new;
	        session('wxuserinfo',$user_new);
	        $this->wxuserinfo = $user_new;
                if($this->openid){
                    $mem = $this->memberModel->where(array('openid'=>$this->openid))->find();
                    if($mem){
                        session('memberinfo',$mem);
                        session('uid',$mem['uid']);
                        $this->memberinfo = session('memberinfo');
                        $this->uid = session('uid');
                    }else{
                        header('Location: /mobile/login');exit;
                    }
                }
	    }else{
                header('Location: /mobile/login');exit;
                return false;
           }
	}
	
	
	
	/*
	 * 获取语言包
	 */
	protected function _getLang($lang="cn"){
	    
	    $language = S('lang');
	    if($language){
	        $this->lang = $language;
	        $this->assign('lang',$language);
	        return true;
	    }
	    
	    $this->langModel = new langModel();
	    $where = array(
	        "status" => 1,
	    );
	    $filed = "cname,".$lang;
	    
	    $res = $this->langModel->getLangList($where,$filed);
	    $language = array();
	    if(!empty($res)){
	        foreach($res as $k=>$v){
	            $language[$v['cname']] = $v[$lang];
	        }
	        S('lang',$language,1);
	        $this->lang = $language;
	        $this->assign('lang',$language);
	    }
	    return false;
	}

	
	//获取数据库中的配置文件
	protected function _getConfig(){
	    $this->configModel = new configModel();
	    $where = array(
	        "status" => 1,
	    );
	    $res = $this->configModel->getConfigList($where);
	    if(!empty($res)){
	        foreach($res as $k=>$v){
	            C($v['cname'],$v['cvalue']);
	        }
	    }
	    return true;
	}
	
	
	//获取数据库中的模板消息id
	protected function _getTmpId(){
	    $tmplModel = new tmplModel();
	    $where = array(
            
	    );
	    $res = $tmplModel->getTmplList($where);
	    $new = array();
	    if(!empty($res)){
	        foreach($res as $k=>$v){
	            $new[$v['tmp_name']] = $v;
	        }
	        
	    }
	    return $new;
	}
	
	
	/*
	 * 从接口获取用户的最新信息
	 */
	protected function _get_user_info($access_token){
	    //请求网址授权接口
	    //
	    $wxuser = $this->wechat->getUserInfo($access_token['openid']);//获取关注者信息
	    
	    if(empty($wxuser)){
			$wxuser = $this->wechat->getOauthUserinfo($access_token['access_token'],$access_token['openid']);//获取授权用户细信息
	        if(empty($wxuser)){
				return false;
			}
	    }
	    
	    $params = array(
	        "openid","unionid","sex","province","city","country","privilege","groupid","language","remark","nickname","subscribe"
	    );
	    $user_data = getParmas($wxuser,$params);//获取含有的参数
	    
	    //昵称非主流乱码过滤
	    if(isset($wxuser['nickname'])){
	        $user_data['nickname'] = str_replace(array(",","'","\"","\\","\/","`"),array("，","＂","＂","","",""),$wxuser['nickname']);//转义
	        $user_data['nickname'] = str_replace(PHP_EOL, '', $wxuser['nickname']);  //去除换行符号
	    }
	    
	    //用户头像  用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像）
	    $headimgurl = set_default($wxuser,"headimgurl");
	    if($headimgurl){
	        $last_two_str = substr($headimgurl,-2);
	        if($last_two_str == "/0"){
	            $pic = substr($headimgurl,0,-2);
	            if($pic){
	                $headimgurl = $pic."/132";
	                $user_data['headimgurl'] = $headimgurl;
	            }
	        }
	    }
	    
	    //关注时间
	    $subscribe_time = set_default($wxuser,"subscribe_time");
	    if($subscribe_time){
	        $user_data['subscribe_time'] = date("Y-m-d H:i:s",$subscribe_time);
	    }
	    
	    return $user_data;
	}
	

	//根据联合id获取用户信息
	public function getMemberInfoByOpenid($openid){
	    $where = array(
	        'openid' => $openid
	    );
	    $res = $this->memberModel->getMember($where);
	    return $res;
	}
	
	//根据uid获取用户信息
	public function getMemberInfobyUid($uid){
	    $where = array(
	        'uid' => $uid
	    );
	    $res = $this->memberModel->getMember($where);
	    return $res;
	}
	

	//更新用户信息
	public function updateMemberInfoByUid($uid,$data){
	    $where = array(
	        'uid' => $uid
	    );
	    if(empty($data) || empty($uid)){
	        return false;
	    }
	    $res = $this->memberModel->editMember($where, $data);
	    return $res;
	}
	
	
	//刷新session userinfo
	public function updateMemberSession($uid=false){
	    
	    if(empty($uid)){
	        return false;
	    }
	    
	    $memberinfo = $this->getMemberInfobyUid($uid);
	    session('memberinfo',$memberinfo);
	    $this->memberinfo = $memberinfo;
	    $this->assign('memberinfo',$this->memberinfo);
	    
	    session('uid',$uid);
	    $this->uid = $uid;
	    
	    return $memberinfo;
	}
	
	
	//tdk seo
	public function setSeo($data){
	    
	    $title = set_default($data,"title",C("SHARE_DEFAULT_TITLE"),true);
	    $description = set_default($data,"description",C("SHARE_DEFAULT_DESC"));
	    $keywords = set_default($data,"keywords",C("SHARE_DEFAULT_DESC"));

	    
	    $this->assign("seo_title",$title);
	    $this->assign("seo_keywords",$keywords);
	    $this->assign("seo_description",$description);
	    
	}
	
	//share wechat
	public function setShare($data=array()){
	
	    $share_title = set_default($data,"title",C("SHARE_DEFAULT_TITLE"));
	    $share_description = set_default($data,"description",C("SHARE_DEFAULT_DESC"));
	    $share_img = set_default($data,"img",C("UPYUN_DOMAIN").C("SHARE_DEFAULT_IMG"));
	
	    //如果没有头像用文章的图片
	    if(!$share_img){
	        //有身份的人用头像
	        if($this->memberinfo['grade_id']>1){
	            $share_img = $this->memberinfo['headimgurl'];
	        }
	    }
	    
	    $share_url = set_default($data,"url");
	    if(!$share_url){
	        $params = set_default($data,"params");
	        $share_url  = $this->_get_share_url($params);
	    }
	
	    $this->assign("share_title",$share_title);
	    $this->assign("share_url",$share_url);
	    $this->assign("share_description",$share_description);
	    $this->assign("share_img",$share_img);
	
	}
	
	
	/*
	 * 获取分享链接
	 */
	protected function _get_share_url($params=''){
	     
	    //拼接分享的网址
	    $share_params = "from=sharelink&suid=".$this->uid;
	
	    if($this->action == 'index'){
	        $link = get_domain()."/mobile/".$this->contro;
	    }else{
	        $link = get_domain()."/mobile/".$this->contro."/".$this->action;
	    }
	     
	    if($params){
	        $share_url = $link."?".$params."&".$share_params;//有传参数的情况
	    }else{
	        $share_url = $link."?".$share_params;
	    }
	     
	    return $share_url;
	}
	
	
	
	//微信分享sdk
	protected function _sharesdk(){
	    
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== off || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			
	    $jssign = $this->wechat->getJsSign($url);
	    $this->assign('jssign',$jssign);
	    return $jssign;

	}
	
	//文件上传
	public function iupload($type="qrcode"){
	
	    $upload = new \Think\Upload();
	    $upload->rootPath  =  "/";
	    $upload->savePath  = "/upload/".$type."/";
	    $filrInfo   =   $upload->upload();
	    if($filrInfo == false){
	        $this -> error = $upload -> getError();
	    }
	    return $filrInfo;
	}
	
	
	/*
	 * 操作失败
	 */
	public function error2($message="失败",$url=""){
	    
	    $seo_data = array(
	        "title" => C("SITE_NAME"),
	    );
	    $this->setSeo($seo_data);
	    
	    $this->assign("message",$message);
	    $this->assign("url",$url);
        $this->display("Common/error");
	    exit;
	}
	
	public function success2($message="成功",$url=""){
	     
	    $seo_data = array(
	        "title" => C("SITE_NAME"),
	    );
	    $this->setSeo($seo_data);
	     
	    $this->assign("message",$message);
	    $this->assign("url",$url);
	    $this->display("Common/success");
	    exit;
	}
	
	/*
	 * 获取购物车商品数量
	 */
	public function getCartNum(){
	    $where = array(
	        "uid" => $this->uid
	    );
	
	    if(!$this->uid){
	        return 0;
	    }
	
	    $sum = $this->cartModel->where($where)->sum('goods_num');
	    return $sum;
	}
	
	
		/*
	 * 自动登录
	 */
	public function wxLogin(){
	    //判断是否登录
	    $this->wxuserinfo = session('wxuserinfo');
	    $this->openid = session('openid');
	    $this->memberinfo['openid'] = $this->wxuserinfo['openid'];
	
	    if(!empty($this->wxuserinfo)){
	        //已经登录过了
	        return true;
	    }
	    $this->wechat = new WechatController();
	
	    //未登录
	    $state = get('state');
	    $session_state = session("state");
	    $code = get("code");
	
	    if(!$state || ($state != $session_state) || !$code){
	        //1. 获取授权地址
	        $state = token();//生成随机state
	        session("state",$state);
	        $scope = "snsapi_base";//  snsapi_userinfo
	        $callback =  get_this_url();
	        $oauth_url = $this->wechat->getOauthRedirect($callback,$state,$scope);// 获取网页授权oAuth跳转地址
	        header('Location: ' . $oauth_url);//去授权页面
	        exit;
	    }
	
	    $access_token = $this->wechat->getOauthAccessToken();
	    $openid = set_default($access_token,'openid');
	    $unionid = set_default($access_token,'unionid');//联合id
		
	    if(!$access_token || !$openid){
	        return false;
	    }
	
	    //获取微信信息成功
	    $this->openid = $openid;
	    $this->unionid = $unionid;
	
	    session('unionid',$unionid);
	    session('openid',$openid);
	
	    //获取最新信息(关注者信息接口)
	    $user_new = $this->_get_user_info($access_token);
	    if($user_new){
	        $user_data = $user_new;
	        session('wxuserinfo',$user_new);
	        $this->wxuserinfo = $user_new;
	    }
	
	    $controller = strtolower(CONTROLLER_NAME);//转成小写
	    $action = strtolower(ACTION_NAME);//转成小写
	
	
	    return true;
	
	}
	
	
}